package 面试刷题.数字马力;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class ch01计算税率 {

    static {
        HandlerFactory.register(new Handler(5000L, 0.03));
        HandlerFactory.register(new Handler(8000L, 0.1));
        HandlerFactory.register(new Handler(17000L, 0.2));
        HandlerFactory.register(new Handler(30000L, 0.25));
        HandlerFactory.register(new Handler(40000L, 0.3));
        HandlerFactory.register(new Handler(60000L, 0.35));
        HandlerFactory.register(new Handler(85000L, 0.45));
    }

    /*模拟客户端*/
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double income = sc.nextDouble();
        System.out.println(HandlerFactory.getTax(income));
    }

    public static class Handler {
        private final double base;    /*税率的左边界(不包含)*/
        private final double rate;  /*税率*/

        public double getBase() {
            return base;
        }

        public double getRate() {
            return rate;
        }

        public Handler(double base, double rate) {
            this.base = base;
            this.rate = rate;
        }
    }

    public static class HandlerFactory {
        static List<Handler> handlers = new ArrayList<>();
        static boolean isOrder = true;   /*是否有序*/

        public static synchronized void register(Handler handler) {
            handlers.add(handler);
            isOrder = false;
        }

        public static void sort() {
            handlers.sort(Comparator.comparingDouble(Handler::getBase));
            isOrder = true;
        }

        public static double getTax(double income) {
            if (!isOrder) {
                synchronized (HandlerFactory.class) {
                    if (!isOrder) {
                        sort();
                    }
                }
            }
            double tax = 0;
            for (int i = handlers.size() - 1; i >= 0; i--) {
                if (income > handlers.get(i).getBase()) {
                    double money = income - handlers.get(i).getBase();
                    tax += (double) (money * handlers.get(i).getRate());
                    /*这里可以加缓存,之后的税是固定的*/
                    income = handlers.get(i).getBase();
                }
            }
            return tax;
        }
    }
}
